import 'package:flutter_account_book/utils/db/entities/account_book.dart';

import '../db_helper.dart';

class AccountBookDao extends DbDao<AccountBook> {
  AccountBookDao({required super.db});
  @override
  String get tableName => "account_books";

  Future<List<AccountBook>> flowAll() async {
    List list = await db.rawQuery(
        'SELECT * FROM $tableName WHERE deleted = 0 ORDER BY `order`');
    return list.map((item) => AccountBook.fromJson(item)).toList();
  }

  Future<AccountBook?> getById(int id) async {
    var result =
        await db.rawQuery('select * from $tableName where id = ?', [id]);
    if (result.isNotEmpty) {
      return AccountBook.fromJson(result[0]);
    }
    return null;
  }

  Future<bool> has(int id) async {
    AccountBook? bookshelf = await getById(id);
    return bookshelf != null;
  }

  Future<int> update(AccountBook bookshelf) async {
    return await db.update(tableName, bookshelf.toJson(),
        where: 'id = ?', whereArgs: [bookshelf.id]);
  }

  Future<int> delete(AccountBook book) async {
    return await db.delete(tableName, where: 'id = ?', whereArgs: [book.id]);
  }

  Future<int> maxOrder() async {
    List result = await db
        .rawQuery('SELECT MAX(`order`) max FROM $tableName where id >= 0');
    if (result.isNotEmpty) {
      return result[0]['max'] as int? ?? 0;
    }
    return 0;
  }

  Future<int> idsSum() async {
    List result =
        await db.rawQuery('SELECT SUM(id) sum FROM $tableName where id >= 0');
    if (result.isNotEmpty) {
      return result[0]['sum'] as int? ?? 0;
    }
    return 0;
  }

  Future<int> getUnusedId() async {
    var id = 1;
    var idsS = await idsSum();
    while (id & idsS != 0) {
      id = id << 1;
    }
    return id;
  }
}
